import json
from flask import request, jsonify
from flask_restx import Namespace, Resource, fields

from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager

from app.models.user import User
from app.utils import make_response
from app.extentions import db

user_api = Namespace('user', prefix='api/user/', description='用户')

user_apimodel = user_api.model('UserModel', {
    'account': fields.String(required=True, description="账号"),
    'password': fields.String(required=True, description="mima"),
    'name': fields.String(required=True, description="xingming"),
})

login_apimodel = user_api.model('LoginModel', {
    'account': fields.String(required=True, description="账号"),
    'password': fields.String(required=True, description="mima")
})


@user_api.route("/login", strict_slashes=False)
@user_api.doc(body=login_apimodel, description="deng lu")
class UserLogin(Resource):
    def post(self):
        data = request.get_json(force=True)
        account = data.get("account")
        password = data.get("password")

        user = User.query.filter_by(account=account).first()
        if not user:
            return make_response(10002, "账号不存在")

        if password != user.password:
            return make_response(10003, "mima cuowu")
        
        resp_data = {
            "uid": user.id,
            "account": user.account,
            "name": user.name,
            "token": create_access_token(identity=user.id)
        }

        return make_response(data=resp_data)


@user_api.route("/logout", strict_slashes=False)
@user_api.doc(description="user logout")
class UserLogout(Resource):

    def post(self):
        return make_response()
    

@user_api.route("/register", strict_slashes=False)
@user_api.doc(body=user_apimodel, description="zhu ce")
class UserRegister(Resource):
    def post(self):
        data = request.get_json(force=True)
        account = data.get("account")
        password = data.get("password")
        name = data.get("name")

        user = User.query.filter_by(account=account).first()
        if user:
            return make_response(10001, "账号已存在")
        
        new_user = User(account=account, password=password, name=name)
        db.session.add(new_user)
        db.session.commit()
        return make_response()